package com.file;

import java.io.*;

/**
 * @Description: 文件读取和写入
 */
public class FIleReadWrite {
    public static void main(String[] args) throws IOException {
        //设定字符编码集
        String encoding = "utf-8";
        File file = new File("f:/test/read.txt");
        InputStreamReader read = new InputStreamReader(
                new FileInputStream(file), encoding);// 考虑到编码格式
        //FileReader read = new FileReader(file); //不考虑转码，可使用FileReader;
        BufferedReader br = new BufferedReader(read);//使用缓冲流按行读取
        StringBuffer sb = new StringBuffer();
        FileWriter fw = new FileWriter("f:/test/write.txt");
        BufferedWriter bw = new BufferedWriter(fw);
        try {

            if (file.exists() && file.isFile()) {
                String lineText = null;
                while ((lineText = br.readLine()) != null) {
                    System.out.println(lineText);
                    sb.append(lineText + "\n");
                }
                bw.write(sb.toString());
                bw.flush();

            } else {
                System.out.println("文件不存在！");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            br.close();
            read.close();
            bw.close();
            fw.close();
        }
    }

}
